
interface IValidMethods {

}

interface IMethodMessage {
  method: string,
  args: any
}

export default function useIframeCommunicate(validMethods: IValidMethods) {
  const methodMessageCreator: (methodName: string, args: any) => IMethodMessage = (methodName: string, args: any) => {
    return {
      method: methodName,
      args,
    }
  }

  const messageListener = (e: MessageEvent) => {
    const { method, args } = e.data
    console.log('method ===>', method)
    if (!method) {
      return
    }

    validMethods[method](args)
  }

  const messagePoster = (iframeElement: HTMLIFrameElement, methodMessage: IMethodMessage) => {
    iframeElement!.contentWindow!.postMessage({
      method: methodMessage.method,
      args: methodMessage.args
    }, iframeElement!.contentWindow!.location.origin)
  }

  return {
    messageListener,
    messagePoster,
    methodMessageCreator
  }
}